package com.jsjosem.aftersales.ui.notifications;


import static com.jsjosem.aftersales.constant.Command.EVENT_CREATE_WORK_ORDER;
import static com.jsjosem.aftersales.utils.CommonUtils.showBigImg;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.DepartmentMenuAdapter;
import com.jsjosem.aftersales.adapter.ImgListViewAdapter;
import com.jsjosem.aftersales.adapter.MySimpleAdapter;
import com.jsjosem.aftersales.api.DepartmentsApi;
import com.jsjosem.aftersales.api.EventApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.component.CustomGridView;
import com.jsjosem.aftersales.constant.Command;
import com.jsjosem.aftersales.data.request.AllotEventRequest;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.CreatorResponse;
import com.jsjosem.aftersales.data.response.CustomerResponse;
import com.jsjosem.aftersales.data.response.CustomerUserResponse;
import com.jsjosem.aftersales.data.response.DepartmentsResponse;
import com.jsjosem.aftersales.data.response.DepartmentsUserResponse;
import com.jsjosem.aftersales.data.response.EventResponse;
import com.jsjosem.aftersales.data.response.ImgResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.data.response.ProductResponse;
import com.jsjosem.aftersales.enums.EventTypeEnum;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.ui.worktickets.MaintainActivity;
import com.jsjosem.aftersales.utils.ScreenSizeUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

public class EventInfoFragment extends Fragment {

    private Context context;
    private CustomGridView imgGridView;
    private final EventResponse eventResponse;
    private TextView tvEventCode;
    private TextView tvFaultDesc;
    private TextView tvDeviceName;
    private TextView tvEventType;
    private TextView tvFinishTime;
    private TextView tvCreateTime;
    private TextView tvCreateBy;
    private TextView tvOriginValue;
    private Button btProcess;
    private Button btCreateWork;
    private EventTypeEnum eventType;
    private Dialog loadingDialog;
    private Retrofit mRetrofit;

    public static EventInfoFragment newInstance(EventResponse eventResponse) {
        return new EventInfoFragment(eventResponse);
    }

    private EventInfoFragment(EventResponse eventResponse) {
        this.eventResponse = eventResponse;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_event_info, container, false);
        context = view.getContext();
        initView(view);
        initData();
        initImgList();
        return view;
    }

    private void initData() {
        tvEventCode.setText(eventResponse.getEvent_number());
        tvFaultDesc.setText(eventResponse.getDescription());
        ProductResponse product = eventResponse.getProduct();
        if (Objects.nonNull(product)) {
            tvDeviceName.setText(product.getmName());
        }
        String status = eventResponse.getStatus();
        eventType = EventTypeEnum.getEnum(status);
        if (eventType == null) {
            eventType = EventTypeEnum.UN_FINISH;
        }
        tvEventType.setText(status);
        // TODO 状态的时间数据
//        tvFinishTime.setText();
        // 根据状态设置按钮的展示
        initProcessBtAndCreateBt();
        tvCreateTime.setText(eventResponse.getUpdated_at());
        CreatorResponse creator = eventResponse.getCreator();
        if (Objects.nonNull(creator)) {
            tvCreateBy.setText(creator.getName());
        }
        tvOriginValue.setText(eventResponse.getCreated_type_text());
    }

    private void initProcessBtAndCreateBt() {
        switch (eventType) {
            case UN_FINISH: // 未完成
                btProcess.setText("完成");
                btCreateWork.setVisibility(View.GONE);
                btProcess.setOnClickListener(view -> {
                    // 完成按钮，打开的是事件回执
                    Bundle bundle = new Bundle();
                    bundle.putString("eventId", eventResponse.getId().toString());
                    Intent intent = new Intent(context, CreateEventReceiptActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                });
                break;
            case FINISH: // 已完成
                btProcess.setVisibility(View.GONE);
                btCreateWork.setVisibility(View.GONE);
                break;
            case UN_DISTRIBUTE: // 待分配
            default:
                btProcess.setText("分配");
                btCreateWork.setVisibility(View.VISIBLE);
                btProcess.setOnClickListener(view -> {
                    // 分配按钮，打开的是员工列表
                    showDepartmentsMenu();
                });
                // 创建工单跳转到创建工单页面
                btCreateWork.setOnClickListener(view -> {
                    Intent intent = new Intent(context, MaintainActivity.class);
                    Bundle bundle = new Bundle();
                    if (eventResponse.getCustomer() != null) {
                        CustomerResponse customer = eventResponse.getCustomer();
                        bundle.putSerializable("customer", customer);
                        CustomerUserResponse customerUser = new CustomerUserResponse();
                        customerUser.setId(Integer.valueOf(eventResponse.getCustomer_user_id()));
                        customerUser.setName(eventResponse.getContact_name());
                        customerUser.setPhone(eventResponse.getContact_telephone());
                        bundle.putSerializable("customerUser", customerUser);
                        if (eventResponse.getProduct() != null) {
                            ProductResponse product = eventResponse.getProduct();
                            bundle.putSerializable("product", product);
                        }
                    }
                    bundle.putInt("event_create_work", EVENT_CREATE_WORK_ORDER);
                    bundle.putString("eventId", eventResponse.getId().toString());
                    intent.putExtras(bundle);
                    startActivity(intent);
                });
        }
    }

    private void initImgList() {
        List<ImgResponse> images = eventResponse.getImages();
        if (CollUtil.isNotEmpty(images)) {
            List<String> urls = images.stream().map(ImgResponse::getImg_url).collect(Collectors.toList());
            ImgListViewAdapter imgListViewAdapter2 = new ImgListViewAdapter(context, urls);
            imgGridView.setAdapter(imgListViewAdapter2);
            imgGridView.setOnItemClickListener((adapterView, view, i, l) -> showBigImg(context, urls, i));
        }
    }

    private void initView(View view) {
        imgGridView = view.findViewById(R.id.img_grid_view);
        tvEventCode = view.findViewById(R.id.tv_event_code);
        tvFaultDesc = view.findViewById(R.id.tv_fault_description);
        tvDeviceName = view.findViewById(R.id.tv_device_name);
        tvEventType = view.findViewById(R.id.tv_event_type);
        tvFinishTime = view.findViewById(R.id.tv_finish_time_value);
        tvCreateTime = view.findViewById(R.id.tv_create_time_value);
        tvCreateBy = view.findViewById(R.id.tv_create_by_value);
        tvOriginValue = view.findViewById(R.id.tv_origin_value);
        btProcess = view.findViewById(R.id.button_process);
        btCreateWork = view.findViewById(R.id.button_create_work);
        mRetrofit = RetrofitClient.getInstance();
    }

    public void showDepartmentsMenu() {
        int currentPage = 1;
        View dialogView = View.inflate(context, R.layout.dialog_department_menu, null);
        Dialog dialog = new Dialog(context, R.style.background_darkens_dialog_style);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(context).getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);

        ListView deptLv = dialogView.findViewById(R.id.area_list);
        ListView deptUserLv = dialogView.findViewById(R.id.staff_list);
        AVLoadingIndicatorView avi = dialogView.findViewById(R.id.avi);

        AtomicInteger selectIndex = new AtomicInteger();
        List<DepartmentsResponse> departmentsResponses = new ArrayList<>();
        Map<String, List<DepartmentsUserResponse>> usersMap = new HashMap<>();
        DepartmentMenuAdapter adapter = new DepartmentMenuAdapter(context, R.layout.area_item_list, departmentsResponses);

        Retrofit mRetrofit = RetrofitClient.getInstance();
        DepartmentsApi departmentsApi = mRetrofit.create(DepartmentsApi.class);
        Call<PageResponse<DepartmentsResponse>> getDepartments = departmentsApi.getDepartments();
        AsyncRequest<PageResponse<DepartmentsResponse>> request = new AsyncRequest<>();
        AsyncRequest<PageResponse<DepartmentsUserResponse>> requestDeptUser = new AsyncRequest<>();

        avi.setVisibility(View.VISIBLE);
        avi.show();
        request.sendRequest(getDepartments, res -> {
            departmentsResponses.addAll(res.getData());
            departmentsResponses.get(0).setSelected(true);

            for (int i = 0; i < res.getData().size(); i++) {
                usersMap.put(res.getData().get(i).getId().toString(), null);
            }

            Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(0).getId(), currentPage, 9999);
            requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                avi.hide();
                deptUserLv.setAdapter(new MySimpleAdapter(context, R.layout.my_simple_item_list, resDeptUser.getData()));
                usersMap.put(departmentsResponses.get(0).getId().toString(), resDeptUser.getData());
            }, err -> {

            });
            adapter.notifyDataSetChanged();
            deptLv.setAdapter(adapter);
        }, err -> Toast.makeText(context, "请求异常，请稍后重试", Toast.LENGTH_LONG).show());

        deptLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            if (usersMap.get(departmentsResponses.get(i).getId().toString()) != null) {
                deptUserLv.setAdapter(new MySimpleAdapter(context, R.layout.my_simple_item_list, usersMap.get(departmentsResponses.get(i).getId().toString())));
            } else {
                Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(i).getId(), currentPage, 9999);
                avi.show();
                requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                    avi.hide();
                    deptUserLv.setAdapter(new MySimpleAdapter(context, R.layout.my_simple_item_list, resDeptUser.getData()));
                    usersMap.put(departmentsResponses.get(i).getId().toString(), resDeptUser.getData());
                }, err -> {

                });
            }
            if (selectIndex.get() != i) {
                departmentsResponses.get(i).setSelected(true);
                departmentsResponses.get(selectIndex.get()).setSelected(false);
                selectIndex.set(i);
            }
            adapter.notifyDataSetChanged();
        });
        dialog.show();
        deptUserLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            List<DepartmentsUserResponse> departmentsUserResponses = usersMap.get(departmentsResponses.get(selectIndex.get()).getId().toString());
            dialog.dismiss();
            loadingShow();
            allotRequest(departmentsUserResponses.get(i).getId());
        });
    }

    private void allotRequest(Long userId) {
        EventApi eventApi = mRetrofit.create(EventApi.class);
        AllotEventRequest allotEventRequest = new AllotEventRequest();
        allotEventRequest.setUser_id(userId);
        Call<BaseResponse<Void>> allotCall = eventApi.allot(eventResponse.getId(), allotEventRequest);
        AsyncRequest<BaseResponse<Void>> request = new AsyncRequest<>();
        request.sendRequest(allotCall, (res) -> {
            loadingDialog.dismiss();
            // 通知事件详情页更新数据
            ListenerManager.getInstance().sendBroadCast(Command.NOTIFY_REFRESH_EVENT_INFO_DATA, null, res.getMsg());
        }, failedMessage -> {
            loadingDialog.dismiss();
            Toast.makeText(context, failedMessage.toString(), Toast.LENGTH_SHORT).show();
        });
    }

    public void loadingShow() {
        loadingDialog = new Dialog(context, R.style.normal_dialog_style);
        View loadingView = View.inflate(context, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }
}
